<template>
  <div class="ip-query-tool">
    <div class="tool-header">
      <h1>IP地址查询</h1>
      <p>查询IP地址的地理位置信息</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 查询主体 -->
        <el-col :span="16">
          <div class="query-section">
            <!-- 查询输入 -->
            <div class="query-input">
              <h3>IP地址查询</h3>
              <div class="input-group">
                <el-input
                  v-model="ipAddress"
                  placeholder="请输入IP地址或域名"
                  size="large"
                  @keyup.enter="queryIP"
                >
                  <template #prepend>
                    <el-icon><Search /></el-icon>
                  </template>
                  <template #append>
                    <el-button @click="queryIP" type="primary" :loading="isQuerying">
                      查询
                    </el-button>
                  </template>
                </el-input>
              </div>
              
              <div class="quick-actions">
                <el-button @click="getMyIP" type="success" size="small">
                  查询我的IP
                </el-button>
                <el-button @click="clearResult" size="small">
                  清空结果
                </el-button>
              </div>
            </div>
            
            <!-- 查询结果 -->
            <div class="query-result" v-if="queryResult">
              <h3>查询结果</h3>
              <div class="result-card">
                <div class="result-header">
                  <div class="ip-info">
                    <div class="ip-address">{{ queryResult.ip }}</div>
                    <div class="ip-type" :class="queryResult.type">{{ queryResult.type }}</div>
                  </div>
                  <div class="location-flag">{{ queryResult.flag }}</div>
                </div>
                
                <div class="result-details">
                  <div class="detail-grid">
                    <div class="detail-item">
                      <div class="detail-label">国家</div>
                      <div class="detail-value">{{ queryResult.country }}</div>
                    </div>
                    <div class="detail-item">
                      <div class="detail-label">省份/州</div>
                      <div class="detail-value">{{ queryResult.region }}</div>
                    </div>
                    <div class="detail-item">
                      <div class="detail-label">城市</div>
                      <div class="detail-value">{{ queryResult.city }}</div>
                    </div>
                    <div class="detail-item">
                      <div class="detail-label">ISP</div>
                      <div class="detail-value">{{ queryResult.isp }}</div>
                    </div>
                    <div class="detail-item">
                      <div class="detail-label">组织</div>
                      <div class="detail-value">{{ queryResult.org }}</div>
                    </div>
                    <div class="detail-item">
                      <div class="detail-label">时区</div>
                      <div class="detail-value">{{ queryResult.timezone }}</div>
                    </div>
                  </div>
                  
                  <div class="coordinates">
                    <div class="coord-item">
                      <div class="coord-label">纬度</div>
                      <div class="coord-value">{{ queryResult.latitude }}</div>
                    </div>
                    <div class="coord-item">
                      <div class="coord-label">经度</div>
                      <div class="coord-value">{{ queryResult.longitude }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 批量查询 -->
            <div class="batch-query">
              <h3>批量IP查询</h3>
              <div class="batch-input">
                <el-input
                  v-model="batchIPs"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入多个IP地址，每行一个"
                  @input="validateBatchIPs"
                />
                <div class="batch-info">
                  <span>已输入 {{ batchIPCount }} 个IP地址</span>
                  <el-button @click="batchQuery" type="primary" :loading="isBatchQuerying" :disabled="batchIPCount === 0">
                    批量查询
                  </el-button>
                </div>
              </div>
              
              <div class="batch-results" v-if="batchResults.length > 0">
                <div class="batch-result-item" v-for="(result, index) in batchResults" :key="index">
                  <div class="batch-ip">{{ result.ip }}</div>
                  <div class="batch-location">{{ result.country }} - {{ result.city }}</div>
                  <div class="batch-isp">{{ result.isp }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 工具和说明 -->
        <el-col :span="8">
          <div class="tools-section">
            <div class="section-header">
              <h3>常用IP</h3>
            </div>
            
            <div class="common-ips">
              <div 
                v-for="ip in commonIPs" 
                :key="ip.address"
                class="ip-item"
                @click="setIP(ip.address)"
              >
                <div class="ip-address">{{ ip.address }}</div>
                <div class="ip-description">{{ ip.description }}</div>
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>支持查询：</h4>
                <ul>
                  <li><strong>IPv4地址：</strong> 如 192.168.1.1</li>
                  <li><strong>IPv6地址：</strong> 如 2001:db8::1</li>
                  <li><strong>域名：</strong> 如 www.example.com</li>
                </ul>
                
                <h4>查询信息：</h4>
                <ul>
                  <li>地理位置信息</li>
                  <li>ISP和运营商</li>
                  <li>经纬度坐标</li>
                  <li>时区信息</li>
                </ul>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ 查询结果仅供参考，可能存在误差</p>
                  <p>⚠️ 某些IP可能无法获取详细信息</p>
                  <p>⚠️ 批量查询请控制数量，避免频繁请求</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const ipAddress = ref('')
const isQuerying = ref(false)
const queryResult = ref(null)
const batchIPs = ref('')
const batchResults = ref([])
const isBatchQuerying = ref(false)

const commonIPs = [
  { address: '8.8.8.8', description: 'Google DNS' },
  { address: '1.1.1.1', description: 'Cloudflare DNS' },
  { address: '114.114.114.114', description: '114 DNS' },
  { address: '223.5.5.5', description: '阿里DNS' },
  { address: '180.76.76.76', description: '百度DNS' }
]

const batchIPCount = computed(() => {
  if (!batchIPs.value.trim()) return 0
  return batchIPs.value.split('\n').filter(ip => ip.trim()).length
})

const validateIP = (ip) => {
  const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/
  const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])*$/
  
  return ipv4Regex.test(ip) || ipv6Regex.test(ip) || domainRegex.test(ip)
}

const queryIP = async () => {
  if (!ipAddress.value.trim()) {
    ElMessage.warning('请输入IP地址或域名')
    return
  }
  
  if (!validateIP(ipAddress.value.trim())) {
    ElMessage.error('请输入有效的IP地址或域名')
    return
  }
  
  isQuerying.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟查询结果
    const mockResult = {
      ip: ipAddress.value.trim(),
      type: ipAddress.value.includes(':') ? 'IPv6' : 'IPv4',
      country: '中国',
      region: '北京市',
      city: '北京市',
      isp: '中国电信',
      org: '中国电信股份有限公司',
      timezone: 'Asia/Shanghai',
      latitude: '39.9042',
      longitude: '116.4074',
      flag: '🇨🇳'
    }
    
    queryResult.value = mockResult
    ElMessage.success('查询成功')
    
  } catch (error) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    isQuerying.value = false
  }
}

const getMyIP = async () => {
  isQuerying.value = true
  
  try {
    // 模拟获取本机IP
    await new Promise(resolve => setTimeout(resolve, 800))
    ipAddress.value = '192.168.1.100'
    await queryIP()
  } catch (error) {
    ElMessage.error('获取本机IP失败')
  } finally {
    isQuerying.value = false
  }
}

const clearResult = () => {
  queryResult.value = null
  ipAddress.value = ''
  batchIPs.value = ''
  batchResults.value = []
  ElMessage.info('已清空结果')
}

const validateBatchIPs = () => {
  // 实时验证批量IP输入
}

const batchQuery = async () => {
  if (batchIPCount.value === 0) {
    ElMessage.warning('请输入要查询的IP地址')
    return
  }
  
  const ips = batchIPs.value.split('\n').filter(ip => ip.trim())
  const invalidIPs = ips.filter(ip => !validateIP(ip.trim()))
  
  if (invalidIPs.length > 0) {
    ElMessage.error(`发现无效IP地址：${invalidIPs.join(', ')}`)
    return
  }
  
  isBatchQuerying.value = true
  batchResults.value = []
  
  try {
    // 模拟批量查询
    for (let i = 0; i < ips.length; i++) {
      await new Promise(resolve => setTimeout(resolve, 500))
      
      const mockResult = {
        ip: ips[i].trim(),
        country: '中国',
        city: '北京市',
        isp: '中国电信'
      }
      
      batchResults.value.push(mockResult)
    }
    
    ElMessage.success(`批量查询完成，共查询 ${ips.length} 个IP`)
    
  } catch (error) {
    ElMessage.error('批量查询失败：' + error.message)
  } finally {
    isBatchQuerying.value = false
  }
}

const setIP = (ip) => {
  ipAddress.value = ip
  ElMessage.success(`已设置IP地址：${ip}`)
}
</script>

<style scoped>
.ip-query-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.query-section,
.tools-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.query-input,
.query-result,
.batch-query {
  margin-bottom: 30px;
}

.query-input h3,
.query-result h3,
.batch-query h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.input-group {
  margin-bottom: 15px;
}

.quick-actions {
  display: flex;
  gap: 10px;
}

.result-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e9ecef;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

.ip-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.ip-address {
  font-size: 1.5rem;
  font-weight: bold;
  color: #333;
}

.ip-type {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
}

.ip-type.IPv4 {
  background: #e3f2fd;
  color: #1976d2;
}

.ip-type.IPv6 {
  background: #f3e5f5;
  color: #7b1fa2;
}

.location-flag {
  font-size: 2rem;
}

.result-details {
  margin-top: 20px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.detail-item {
  background: white;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.detail-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.detail-value {
  font-size: 1rem;
  font-weight: 500;
  color: #333;
}

.coordinates {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.coord-item {
  text-align: center;
  background: white;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  min-width: 120px;
}

.coord-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.coord-value {
  font-size: 1.1rem;
  font-weight: bold;
  color: #667eea;
}

.batch-input {
  margin-bottom: 20px;
}

.batch-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  color: #666;
}

.batch-results {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.batch-result-item {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
  border: 1px solid #e9ecef;
}

.batch-ip {
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.batch-location {
  color: #666;
  margin-bottom: 3px;
}

.batch-isp {
  font-size: 0.9rem;
  color: #999;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.common-ips {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.ip-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.ip-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.ip-address {
  font-size: 1rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.ip-description {
  font-size: 0.9rem;
  color: #666;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .result-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .coordinates {
    flex-direction: column;
    align-items: center;
  }
  
  .batch-info {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
}
</style>
